package com.lijin.batchsys.framework.control;

import java.util.Date;

import org.apache.log4j.Logger;

import com.lijin.batchsys.framework.common.ApplicationContextHolder;
import com.lijin.batchsys.framework.common.AssertUtil;
import com.lijin.batchsys.framework.common.BatchSysException;
import com.lijin.batchsys.framework.common.BatchUtil;
import com.lijin.batchsys.framework.dao.model.StepInfo;
import com.lijin.batchsys.framework.enums.RunningStatus;

public class BatchSysStep {
	
	private static final Logger logger = Logger.getLogger(BatchSysStep.class);
	
	private StepInfo stepInfo;
	
	public BatchSysStep(StepInfo stepInfo) {
		this.stepInfo = stepInfo;
	}
	
	public final void execute(StepExecContext stepCtx) {
		String stepSummary = null;
		try {
			AssertUtil.objIsNull(stepCtx, "步骤执行上下文环境不能为null");
			stepSummary = stepCtx.getStepSummary();
			logger.info("步骤" + stepSummary + "执行开始...");
			// 获取批次日期
			String batchDateStr = stepCtx.getBatchContext().getBatchDateStr();
			AssertUtil.strIsBlank(batchDateStr, "批量日期为空");
			Date batchDate = BatchUtil.parse(batchDateStr);
			// 获取业务Bean
			AssertUtil.objIsNull(stepInfo, "步骤信息不能为null");
			IBatchSysTask task = ApplicationContextHolder.getBean(stepInfo.getStepBeanName());
			AssertUtil.objIsNull(task, "未找到指定的业务Bean:" + stepInfo.getStepBeanName());
			
			// 业务类开始执行
			task.execute(batchDate);
			stepCtx.setStatus(RunningStatus.COMPLETED);
			
			logger.info("步骤" + stepSummary + "执行完成...");
		} catch (Exception e) {
			logger.error("步骤" + stepSummary + "执行出错...", e);
			stepCtx.setStatus(RunningStatus.FAILED);
			// 包装成BatchSysException抛出
			throw new BatchSysException("步骤" + stepSummary + "执行出错...", e);
		} finally {
			// 执行完成后将当前时间标记为步骤完成时间
			stepCtx.setEndTm(new Date());
			stepCtx.logContext();
		}
	}
	
	/**
	 * 当前步骤是否可以跳过
	 * @return
	 */
	public boolean canSkip() {
		return stepInfo.canSkip();
	}

	public StepInfo getStepInfo() {
		return stepInfo;
	}
}
